package com.ytzl.itrip.controller;

import com.ytzl.itrip.common.DtoUtil;
import com.ytzl.itrip.common.EmptyUtils;
import com.ytzl.itrip.common.ErrorCode;
import com.ytzl.itrip.dto.Dto;
import com.ytzl.itrip.exception.UserLoginFailedException;
import com.ytzl.itrip.pojo.ItripUser;
import com.ytzl.itrip.service.TokenService;
import com.ytzl.itrip.vo.ItripTokenVO;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;

/**
 * Created by sam on 2018/2/8.
 */
@Controller
@RequestMapping("/api")
public class LoginController extends BaseController {


    @ApiOperation(value = "登录", httpMethod = "POST", produces = "application/json", response = Dto.class, notes = "用户输入用户名密码登录")
    @RequestMapping(value = "/dologin", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public Dto dologin(@RequestParam @ApiParam(name = "name", value = "登录用户名") String name,
                       @RequestParam @ApiParam(name = "password", value = "密码") String password, HttpServletRequest request) {
        if (EmptyUtils.isNotEmpty(name) && EmptyUtils.isNotEmpty(password)) {
            //登录
            ItripUser itripUser;
            try {
                itripUser = itripUserService.login(name, md52Value(password));
            } catch (UserLoginFailedException e) {
                e.printStackTrace();
                return DtoUtil.returnFail(e.getMessage(), ErrorCode.AUTH_AUTHENTICATION_FAILED);
            } catch (Exception e) {
                e.printStackTrace();
                return DtoUtil.returnFail(e.getMessage(), ErrorCode.AUTH_UNKNOWN);
            }
            if (EmptyUtils.isNotEmpty(itripUser)) {
                //登录成功
                //构建token
                String token = tokenService.generateToken(request.getHeader("user-agent"), itripUser);
                //保存token
                tokenService.save(token, itripUser);
                //生成前端要的数据
                ItripTokenVO itripTokenVO = new ItripTokenVO(token, //
                        Calendar.getInstance().getTimeInMillis() + TokenService.SESSION_TIMEOUT * 1000,//
                        Calendar.getInstance().getTimeInMillis());
                return DtoUtil.returnDataSuccess(itripTokenVO);
            } else {
                return DtoUtil.returnFail("用户名或密码错误", ErrorCode.AUTH_AUTHENTICATION_FAILED);
            }
        } else {
            return DtoUtil.returnFail("参数错误！请检查提交参数名称是否正确", ErrorCode.AUTH_PARAMETER_ERROR);
        }
    }

    @ApiOperation(value = "注销", httpMethod = "GET", produces = "application/json", notes = "用户退出登录", response = Dto.class)
    @RequestMapping(value = "/logout", method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public Dto logout(HttpServletRequest request) {
        String token = request.getHeader("token");
        if (!tokenService.validate(request.getHeader("user-agent"), token))
            return DtoUtil.returnFail("Token无效", ErrorCode.AUTH_TOKEN_INVALID);
        try {
            tokenService.remove(token);
            return DtoUtil.returnSuccess("注销成功");
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("注销失败", ErrorCode.AUTH_UNKNOWN);
        }
    }

}
